package com.movitech.mobile.cz.base.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sys.bizvo.RegionalCompanyRequestVO;
import com.movitech.mobile.cz.base.sys.bizvo.RegionalCompanySaveRequestVO;
import com.movitech.mobile.cz.base.sys.entity.SProject;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.entity.ext.ExtSRegionalCompany;
import com.movitech.mobile.cz.base.sys.entity.ext.SProjectRequestVO;
import com.movitech.mobile.cz.base.sys.entity.ext.SRegionCompanyRequestVO;
import com.movitech.mobile.cz.base.sys.mapper.SRegionalCompanyMapper;
import com.movitech.mobile.cz.base.sys.mapper.ext.ExtSRegionalCompanyMapper;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.sys.service.SysAreaService;
import com.movitech.mobile.cz.base.sys.service.SysUserService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 地区公司 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sRegionalCompanyService")
@Transactional
public class SRegionalCompanyServiceImpl extends ServiceImpl<SRegionalCompanyMapper, SRegionalCompany> implements SRegionalCompanyService {

	private final static Logger logger = Logger.getLogger(SRegionalCompanyServiceImpl.class);

	@Autowired
	private ExtSRegionalCompanyMapper extSRegionalCompanyMapper;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
    private SysAreaService sysAreaService;

	@Override
	public String getRegionalCompanyNames(String[] regionalCompanyIdArr) {
		return extSRegionalCompanyMapper.getRegionalCompanyNames(regionalCompanyIdArr);
	}

	@Override
	public PageCode findRegionalCompanyList(RegionalCompanyRequestVO regionalCompanyRequestVO) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageFlag", regionalCompanyRequestVO.getPageFlag());
		map.put("pageSize", regionalCompanyRequestVO.getPageSize());
		if(regionalCompanyRequestVO.getPageSize() == 0){
			regionalCompanyRequestVO.setPageSize(10);
		}
		PageCode pageCode = new PageCode(regionalCompanyRequestVO.getPageNumber(), regionalCompanyRequestVO.getPageSize());
		map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());

		map.put("regionalCompanyCode", regionalCompanyRequestVO.getRegionalCompanyCode());
		map.put("regionalCompanyName", regionalCompanyRequestVO.getRegionalCompanyName());
		map.put("areaIdList", regionalCompanyRequestVO.getAreaIdList());

		Integer count = extSRegionalCompanyMapper.findRegionalCompanyListCount(map);
		pageCode.setCount(count == null ? 0 : count);
		List<ExtSRegionalCompany> ls = extSRegionalCompanyMapper.findRegionalCompanyList(map);
		for(ExtSRegionalCompany obj:ls){
			if(StringUtils.isNotEmpty(obj.getSupplierMngUsers())){
				String names=sysUserService.getSysUserNameByIds(obj.getSupplierMngUsers());
				if(StringUtils.isNotEmpty(names))obj.setSupplierMngUserNames(names);
			}

			if(StringUtils.isNotEmpty(obj.getAreaIds())){
				String areaNames = sysAreaService.getSysAreaNamesByIds(obj.getAreaIds());

				if(StringUtils.isNotEmpty(areaNames)){
					obj.setAreaNames(areaNames);
				}
			}

		}
		pageCode.setList(ls);
		return pageCode;
	}

	@Override
	public SRegionalCompany getRegionalCompanyByMngUser(String userId) {
		return extSRegionalCompanyMapper.getRegionalCompanyByMngUser(userId);
	}

	@Override
	public List<ExtSRegionalCompany> getGroupRegionalCompany(){
		return extSRegionalCompanyMapper.getGroupRegionalCompany();
	}

	public List<SRegionalCompany> getRegionalCompanyByCode(String code) {
		SRegionalCompany searchSRegionalCompany = new SRegionalCompany();
		searchSRegionalCompany.setRegionalCompanyCode(code);
		EntityWrapper<SRegionalCompany> wrapper = new EntityWrapper<SRegionalCompany>();
        wrapper.setEntity(searchSRegionalCompany);
        return selectList(wrapper);
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
	@Override
	public RestReturnResult<Object> saveOrUpdateRegionalCompany(RegionalCompanySaveRequestVO regionalCompanySaveRequestVO) throws Exception {
		RestReturnResult<Object> restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		try{

			if(regionalCompanySaveRequestVO != null && StringUtils.isNotBlank(regionalCompanySaveRequestVO.getId())){//同步过来的，只能update
				SRegionalCompany sRegionalCompany = baseMapper.selectById(regionalCompanySaveRequestVO.getId());
				if(sRegionalCompany != null){
					sRegionalCompany.setSupplierMngUsers(regionalCompanySaveRequestVO.getSupplierMngUsers());

					boolean flag = this.updateSRegionalCompany(sRegionalCompany);

					if(flag){
						restResult =RestReturnResult.success();
					}else{
						restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[9], CommonConstants.ERROR_DESCS[9]);
					}

				}else{
					restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
				}

			}else{
				restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
			}

		}catch(Exception e){
			e.printStackTrace();
			logger.error("================saveOrUpdateRegionalCompany=====e:======="+e.getMessage());
			throw new Exception(e.getMessage());
		}

		return restResult;
	}

	@Override
	public boolean updateSRegionalCompany(SRegionalCompany sRegionalCompany) {

		if(sRegionalCompany != null && StringUtils.isNoneBlank(sRegionalCompany.getId())){

			String userId = UserUtils.getCurrentUserId();
			Date updateDate = new Date();
			sRegionalCompany.setUpdateBy(userId);
			sRegionalCompany.setUpdateDate(updateDate);

			int i = baseMapper.updateById(sRegionalCompany);

			return i > 0;
		}

		return false;
	}

	@Override
	public List<String> findAdminCIdsBySupplierId(String supplierId) {

		return extSRegionalCompanyMapper.getAdminCIdsBySupplierId(supplierId);
	}

	@Override
	public SRegionalCompany selectByCode(String code) {
		return extSRegionalCompanyMapper.selectByCode(code);
	}

	@Override
	public SRegionalCompany getRootRegionalCompany() {
		return extSRegionalCompanyMapper.getRootRegionalCompany();
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
	@Override
	public void batchAdd(List<SRegionCompanyRequestVO> sRegionCompanyList) {
		try {
			if (sRegionCompanyList != null && sRegionCompanyList.size() > 0) {
				for (SRegionCompanyRequestVO sRegionCompany : sRegionCompanyList) {
					if (com.movitech.mobile.cz.base.common.util.StringUtils.isEmpty(sRegionCompany.getRegionCompanyCode())) {
						continue;
					}
					SRegionalCompany sRegionalCompany = this.selectByCode(sRegionCompany.getRegionCompanyCode());
					if (sRegionalCompany == null) {
						sRegionalCompany = new SRegionalCompany();
						sRegionalCompany.setRegionalCompanyCode(sRegionCompany.getRegionCompanyCode());
						sRegionalCompany.setRegionalCompanyName(sRegionCompany.getRegionCompanyName());
						sRegionalCompany.setRcType(2);
						sRegionalCompany.setBaseFeilds(UserUtils.getCurrentUserId(),"",sRegionCompany.getStatus(),true);
						this.insert(sRegionalCompany);
					} else {
						if (sRegionalCompany.getRegionalCompanyCode().equals(sRegionCompany.getRegionCompanyCode())) {
							sRegionalCompany.setRegionalCompanyName(sRegionCompany.getRegionCompanyName());
							sRegionalCompany.setDelFlag(sRegionCompany.getStatus());
							sRegionalCompany.setBaseFeilds(UserUtils.getCurrentUserId(),"",sRegionCompany.getStatus(),false);
							this.updateById(sRegionalCompany);
						}
					}
				}
			}
		} catch (RuntimeException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
}
